import React, { Component } from 'react';
import { Card, Tree, Input, Tabs, Table, Spin, Tooltip } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import styles from './index.less';
import * as apis from '@/services/SystemMgr';
import Mpagination from '../components/Mpagination';

const { Search } = Input;
const { TabPane } = Tabs;

@connect(state => ({
  systemManageItems: state.SystemManageItems,
}))
class Structure extends Component {
  constructor() {
    super();
    this.state = {
      expandedKeys: ['00000000'],
      autoExpandParent: true,
      loading: true,
      tabChecked: '1',
      total: '0', // 列表的总条数
      current: '1', // 当前页数
      pageSize: '20', // 每页条数
      pages: '0', // 总页数
      usercn: '', // 搜索名称
      departmentnumber: '', // 部门id
      searchValue: '',
      tableIptVlue: '',
      // 岗位
      OrgPositionColumns: [
        {
          title: '序号',
          dataIndex: 'key',
          align: 'center',
          width: 50,
        },
        {
          key: 'sentryName',
          title: '岗位名称',
          dataIndex: 'sentryName',
          align: 'left',
          width: 300,
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          key: 'sentryCode',
          title: '岗位定义编码',
          dataIndex: 'sentryCode',
          align: 'left',
          width: 100,
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          key: 'departmentName',
          title: '所属部门全称',
          dataIndex: 'departmentName',
          align: 'left',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
      ],
      OrgPositionData: [],
      // 用户
      userColumns: [
        {
          title: '序号',
          dataIndex: 'key',
          align: 'center',
          width: 50,
          fixed: 'left',
        },
        {
          title: '用户账号',
          dataIndex: 'accountNumber',
          key: 'accountNumber',
          align: 'left',
          width: 100,
          fixed: 'left',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '用户名称',
          dataIndex: 'accountName',
          key: 'accountName',
          align: 'left',
          width: 70,
          fixed: 'left',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '岗位组名称',
          dataIndex: 'jobname',
          key: 'jobname',
          align: 'left',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '岗位名称',
          dataIndex: 'sentryName',
          key: 'sentryName',
          align: 'center',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '登录名',
          dataIndex: 'landName',
          key: 'landName',
          align: 'left',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '用户类型',
          dataIndex: 'userType',
          key: 'userType',
          align: 'left',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '手机',
          dataIndex: 'phone',
          key: 'phone',
          align: 'left',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          key: 'email',
          align: 'left',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '部门编码',
          dataIndex: 'departmentCode',
          key: 'departmentCode',
          align: 'left',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '用户性别',
          dataIndex: 'gender',
          key: 'gender',
          align: 'left',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
      ],
      userData: [],
    };
  }

  // 初始化
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'SystemManageItems/init',
      payload: {},
    });
    this.getOrgPositionPage();
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      expandedKeys: nextProps.systemManageItems.expandedKeys,
    });
  }

  async getUserPage(current = '1', usercn = '', departmentnumber = '', pageSize = '20') {
    this.setState({
      userData: [],
    });
    // 获取用户信息表
    const params = {
      current, // 当前第几页
      departmentnumber, // 部门id
      pageSize: `${pageSize}`, // 每页条数
      usercn, // 用户名称
    };
    const getUserData = await apis.getUserPageListUsingGET({ params });
    if (getUserData.code === 1) {
      const arr = [];
      getUserData.data.list.map((item, index) => {
        const obj = {
          key: getUserData.data.pageSize * (getUserData.data.current - 1) + index + 1,
          accountNumber: item.username,
          accountName: item.usercn,
          sentryName: item.positionname,
          jobname: item.jobname,
          landName: item.alias,
          userType: item.usertype,
          phone: item.mobile,
          email: item.mail,
          departmentCode: item.departmentnumber,
          gender: item.genderId,
        };
        arr.push(obj);
        return arr;
      });
      this.setState({
        userData: arr,
        total: getUserData.data.total,
        pageSize: getUserData.data.pageSize,
        pages: getUserData.data.pages,
        current: getUserData.data.current,
        loading: false,
      });
    }
  }

  async getOrgPositionPage(current = '1', usercn = '', departmentnumber = '', pageSize = '20') {
    this.setState({
      OrgPositionData: [],
    });
    const params = {
      current, // 当前第几页
      belongDepId: departmentnumber, // 部门id
      pageSize, // 每页条数
      jobName: usercn, // 岗位名称
    };
    const getOrgPositionData = await apis.getOrgPositionPageUsingGET({ params });
    if (getOrgPositionData && getOrgPositionData.code === 1) {
      const arr = [];
      getOrgPositionData.data.list.map((item, index) => {
        const obj = {
          key: getOrgPositionData.data.pageSize * (getOrgPositionData.data.current - 1) + index + 1,
          sentryName: item.jobName,
          sentryCode: item.belongJobDefId,
          departmentName: item.belongDepFullName,
        };
        arr.push(obj);
        return arr;
      });
      this.setState({
        OrgPositionData: arr,
        total: getOrgPositionData.data.total,
        pageSize: getOrgPositionData.data.pageSize,
        pages: getOrgPositionData.data.pages,
        current: getOrgPositionData.data.current,
        loading: false,
      });
    }
  }

  // 搜索表格
  searchName = value => {
    this.setState({
      usercn: value,
      loading: true,
    });

    if (this.state.tabChecked === '1') {
      this.getOrgPositionPage('1', value, this.state.departmentnumber, this.state.pageSize);
    } else if (this.state.tabChecked === '2') {
      this.getUserPage('1', value, this.state.departmentnumber, this.state.pageSize);
    }
  };

  // 获取分页点击的页数
  handlePaginationChange = (current, pageSize) => {
    this.setState({ loading: true });
    if (this.state.tabChecked === '1') {
      this.getOrgPositionPage(
        `${current}`,
        this.state.usercn,
        this.state.departmentnumber,
        pageSize,
      );
    } else if (this.state.tabChecked === '2') {
      this.getUserPage(`${current}`, this.state.usercn, this.state.departmentnumber, pageSize);
    }
  };

  // 修改每页参数
  onShowSizeChange = (current, pageSize) => {
    this.handlePaginationChange(current, pageSize);
  };

  // 点击组织架构树获取部门id
  clickTreeNode = selectedKeys => {
    console.log(selectedKeys);
    this.setState({
      departmentnumber: selectedKeys[0],
      loading: true,
    });
    if (this.state.tabChecked === '1') {
      this.getOrgPositionPage('1', this.state.usercn, selectedKeys[0], this.state.pageSize);
    } else if (this.state.tabChecked === '2') {
      this.getUserPage('1', this.state.usercn, selectedKeys[0], this.state.pageSize);
    }
  };

  // 切换导航
  clickTabState = checked => {
    this.setState({
      total: '0', // 列表的总条数
      current: '1', // 当前页数
      pageSize: '20', // 每页条数
      pages: '0', // 总页数
      usercn: '', // 搜索名称
      departmentnumber: '', // 部门id
      tabChecked: checked,
      tableIptVlue: '',
      loading: true,
    });
    if (checked === '1') {
      this.getOrgPositionPage();
    } else if (checked === '2') {
      this.getUserPage();
    }
  };

  // 搜索组织树
  searchOrgTree = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'SystemManageItems/searchOrgTree',
      payload: value,
    });
    this.setState({
      // expandedKeys: ['56569342438', '99174100492'],
      autoExpandParent: true,
    });
  };

  // 树的展开收起
  handleTreeOnExpand = expandedKeys => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  render() {
    const { expandedKeys, autoExpandParent, tabChecked } = this.state;
    const { systemManageItems } = this.props;
    const tableHeight = document.body.clientHeight - 255;

    return (
      <div className={styles.Structure}>
        <PageHeaderWrapper breadcrumb={null} title="组织架构">
          <Card>
            <div className="content">
              <div className="left">
                <h3>组织树</h3>
                <div className="tree">
                  <Search placeholder="请输入组织名搜索" onSearch={this.searchOrgTree} />
                  <div className="tree-box">
                    {systemManageItems.orgTree && systemManageItems.orgTree.length ? (
                      <Tree
                        onExpand={this.handleTreeOnExpand}
                        expandedKeys={expandedKeys}
                        defaultSelectedKeys={expandedKeys}
                        autoExpandParent={autoExpandParent}
                        onSelect={this.clickTreeNode}
                        treeData={systemManageItems.orgTree}
                      />
                    ) : (
                      <Spin tip="加载中..." />
                    )}
                  </div>
                </div>
              </div>
              <div className="right">
                <div className="table">
                  <Tabs
                    defaultActiveKey="1"
                    tabBarExtraContent={
                      <Search
                        placeholder={
                          tabChecked === '1' ? '请输入岗位名称搜索' : '请输入用户名称搜索'
                        }
                        onChange={e => {
                          this.setState({ tableIptVlue: e.target.value });
                        }}
                        value={this.state.tableIptVlue}
                        onSearch={this.searchName}
                        style={{ width: 180, marginTop: 9 }}
                      />
                    }
                    onChange={this.clickTabState}
                  >
                    <TabPane tab="岗位" key="1">
                      <Table
                        columns={this.state.OrgPositionColumns}
                        dataSource={this.state.OrgPositionData}
                        bordered
                        pagination={false}
                        scroll={{ y: tableHeight }}
                        size="middle"
                        loading={this.state.loading}
                      />
                    </TabPane>
                    <TabPane tab="用户" key="2">
                      <Table
                        columns={this.state.userColumns}
                        dataSource={this.state.userData}
                        bordered
                        pagination={false}
                        loading={this.state.loading}
                        scroll={{ y: tableHeight, x: 1300 }}
                        size="middle"
                      />
                    </TabPane>
                  </Tabs>
                </div>
                <Mpagination
                  total={this.state.total}
                  pageSize={this.state.pageSize}
                  current={this.state.current}
                  pages={this.state.pages}
                  onShowSizeChange={(current, pageSize) => this.onShowSizeChange(current, pageSize)}
                  handlePaginationChange={this.handlePaginationChange}
                />
              </div>
            </div>
          </Card>
        </PageHeaderWrapper>
      </div>
    );
  }
}

export default Structure;
